﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;

namespace ZhimeiSoft.Framework.Server.Base
{
    public class BaseDal
    {
        #region 变量
        private Database _db;
        #endregion

        #region 属性
        /// <summary>
        /// Database对象
        /// </summary>
        protected Database DB
        {
            get { return _db; }
        }

        #endregion

        #region 构造函数
        /// <summary>
        /// 默认的构造函数
        /// </summary>
        public BaseDal()
        {
            try
            {
                _db = DatabaseFactory.CreateDatabase("CharmManagerDB");
            }
            catch (Exception ex)
            {
                throw ex;
            }
            
        }
        #endregion

        #region 私有函数

        #endregion

        #region 公有函数

        /// <summary>
        /// 获取一个打开的数据库连接
        /// </summary>
        /// <returns>一个打开的数据库连接</returns>
        public IDbConnection GetConnection()
        {
            IDbConnection connection = _db.CreateConnection();
            connection.Open();
            return connection;
        }

        public void CloseConnection(IDbConnection connection)
        {
            if (connection != null)
            {
                connection.Close();
                connection.Dispose();
            }
        }

        /// <summary>
        /// 获取最大的ID
        /// </summary>
        /// <param name="strTableName">数据库表名</param>
        /// <param name="strFieldName">数据库字段名</param>
        /// <returns>最大的ID</returns>
        public int GetMaxID(string strTableName, string strFieldName)
        {
            string strSQL = string.Format("SELECT ISNULL(MAX({0}), 0) FROM {1}", strFieldName, strTableName);
            DbCommand cmdSelect = DB.GetSqlStringCommand(strSQL);
            return (int)DB.ExecuteScalar(cmdSelect);
        }

        public DataSet GetDataSet(string sql)
        {
            DbCommand cmd = DB.GetSqlStringCommand(sql);
            return _db.ExecuteDataSet(cmd);
        }

        #endregion
    }
}
